import axios from 'axios';
import qs from 'qs';
import store from '../store/index';
import router from '../router/index';
import {getCookie} from './function';
import {getAccessToken} from '@/api';


// console.log('store.state:', store.state)
// console.log('uniacid:', store.state.urlParams)
// console.log(`canshu:${store.state.urlParams.uniacid}/${store.state.urlParams.uniacid}`)
const axiosServer = axios.create({
	//baseURL: `${BASE_PRE_URL}addons/wg_live/api/liveapi/`,
  	baseURL: '/api/',
	//baseURL: '/addons/wg_live/api/liveapi/',
	timeout: 10000,
	headers: {
		'X-Requested-With': 'XMLHttpRequest',
		'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
	},
	transformRequest: [function(data) {
	    const ret = qs.stringify(data)
	    return ret;
	}]
});

//axiosServer.defaults.timeout = 3000;

axiosServer.interceptors.request.use(function(config){
	localStorage.setItem('access-token', 'NGFiYTUyMDA5MjRjOWZiMTczMDZiYTgxNDlkZGM2Y2U=')
	let token = localStorage.getItem('access-token');

	//console.log(token)
	config.headers.common['access-token'] = getCookie() || 'NGFiYTUyMDA5MjRjOWZiMTczMDZiYTgxNDlkZGM2Y2U=' || getCookie() || '';
	config.headers['access-token'] = getCookie() || 'NGFiYTUyMDA5MjRjOWZiMTczMDZiYTgxNDlkZGM2Y2U=' || getCookie() || '';
	//config.headers.common['access-token'] = getCookie() || '';
	// config.params = {...config.params, ...{
	// 		//token: getCookie() || ''
	// 		'access-token': getCookie() || 'NGFiYTUyMDA5MjRjOWZiMTczMDZiYTgxNDlkZGM2Y2U=' || getCookie() || ''
	// 	}
	// };
	config.baseURL += `${store.state.urlParams.uniacid}/${store.state.urlParams.type}/`;
	//config.baseURL += `/3/1/`;
	return config;
}, function(error){
	return Promise.reject(error);
});



axiosServer.interceptors.response.use(function(response){
	let result = response.data;
	let currentPage = encodeURIComponent(location.href);

	let token = getCookie();
	if(token){
		localStorage.setItem('access-token', getCookie());
	}
	//localStorage.setItem('access-token', getCookie());

	// 如果未授权直接跳转出去
	if(result.code == 401){
		setTimeout(()=>{
			location.href = `${result.data.login_url}?page=${currentPage}`;
		}, 30);
		return;
	}


	//localStorage.setItem('access-token', getCookie());
	//let token = localStorage.getItem('access-token');
	// let token = localStorage.getItem('access-token');
	// if(!token){
	// 	if(response.headers['access-token']){
	// 		token = response.headers['access-token'];
	// 		localStorage.setItem('access-token', token);
	// 		return response.data;
	// 	}

	// 	if(!token) {
	// 		localStorage.setItem('access-token', getCookie());
	// 		return response.data;
	// 	}
	// }

	return response.data;
},function(error){
	return Promise.reject(error);
});

export default axiosServer;
